# -*- coding: utf-8 -*-
from datetime import date
from urllib2 import URLError
import json

from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.template.loader import render_to_string

from export.distributors.stack import Stack
from export.distributor import Distributor
from export.importIntoMagento import ImportIntoMagento
from export.models import Currency
from export.services import UploadCatalog, sendReport


def view(request):
    """
    Main page Export/Import

    :param request: http parameters
    :return: show main page of export/import
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    if request.user.is_superuser:
        form = UploadCatalog(request.POST, request.FILES)
        if form.is_valid():
            # try:
            if int(form.data['type']) == 1:
                try:
                    data = HttpResponse(mimetype='text/csv')
                    data['charset'] = 'cp1251'
                    data.content, name = ImportIntoMagento().importProducts(json.loads(form.getFileContent()))
                    data['Content-Disposition'] = 'attachment; filename="%s.csv"' % name
                    return data
                except URLError:
                    form = UploadCatalog()
                    return render_to_response('export/view.html', {'form': form, 'error': 'не працює поставщик'})
                except ValueError, e:
                    form = UploadCatalog()
                    return render_to_response('export/view.html',
                                              {'form': form, 'error': 'не правильний формат даних:%s' % e})
            elif int(form.data['type']) == 2:
                Distributor().updateRules(form.getFileContent(), form.data['delimetr'].encode('utf-8'))
            elif int(form.data['type']) == 3:
                Distributor().updateAvailFromPrice('mti', form.getMtiSKU())
            elif int(form.data['type']) == 4:
                Distributor().updateAvailFromPrice('ug', form.getUgSKU())
            else:
                Stack(form.getFileContent()).setPrice()
            # except:
            #     return render_to_response('export/view.html', {'form': form, 'logs': Distributor().getAllLog(),
            #                                                    'error': 'не правильний формат даних'})
        else:
            form = UploadCatalog()
        return render_to_response('export/view.html', {'form': form, 'logs': Distributor().getAllLog()})
    return HttpResponseRedirect(reverse('home'))


def set_currency(request):
    """
    Setting currency exchange rate

    :param request: GET parameter @currency - current currency
    :return: redirected to main page of export/import
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    if request.user.is_superuser:
        if request.GET.has_key('currency'):
            currency = Currency.objects.all()[0]
            currency.currency = request.GET['currency']
            currency.save()
        return HttpResponseRedirect('/export/')
    return HttpResponseRedirect(reverse('home'))


def price(request):
    """
    Update price and available products in magento

    :param request: http parameter can take GET parameter @category - name of update category
    :return: @ok if update was successful
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    if request.user.is_superuser:
        if request.GET.has_key('category'):
            Distributor().updatePrice(request.GET['category'])
        Distributor().updatePrice()
        year, month, day = str(date.today()).split('-')
        context = Distributor().getLogInfo('%s-%s-%s' % (year, month, day))
        html = render_to_string('export/mail_log_info.html', context)
        sendReport(html, 'olexsbas@gmail.com', 'Daily report service %s-%s-%s' % (year, month, day))
        return HttpResponse('ok')
    return HttpResponseRedirect(reverse('home'))


def price_rule(request):
    """
    Page of list rules creating price. If GET parameter - delete current rule. If POST parameters adding new rule.

    :param request.GET['ruleid']: id of rule pricing
    :param request.POST['distributors']: name of distributor
    :param request.POST['category']: name of category
    :param request.POST['price_level']: price level in distributor
    :param request.POST['price_add']: how much add to price
    :return: redirected to main page of export/import
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    if request.user.is_superuser:
        distributor = Distributor()
        if request.GET.has_key('ruleid'):
            distributor.delRule(request.GET['ruleid'])
        elif request.method == 'POST':
            try:
                distributor.addRule(request.POST)
            except Exception:
                return render_to_response('export/price.html',
                                          {'rules': distributor.getRules(), 'error': 'Не правильний формат даних'})
        return render_to_response('export/price.html', {'rules': distributor.getRules()})
    return HttpResponseRedirect(reverse('home'))


def categories(request):
    """
    Page of list of all categories in distributor.

    :param request: http parameters
    :return: show list of all categories in distributor
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    if request.user.is_superuser:
        return render_to_response('export/categories.html', {'categories': Distributor().getCategories()})
    return HttpResponseRedirect(reverse('home'))


def diff_sku(request):
    """
    Page where show different name by sku between stek and magento.

    :param request: http parameters
    :return: list of name stek, magento and sku
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    if request.user.is_superuser:
        products = Distributor().getSku()
        return render_to_response('export/diff_sku.html', locals())
    return HttpResponseRedirect(reverse('home'))


def log_info(request, year, month, day):
    """
    Page show information in log file.

    :param request: http parameters
    :param request.POST: filtering parameters: id, sku, name, b2b_category, last_price, price, avail, change_price,
    change_avail.
    :param year: year of date logging
    :param month: month of date logging
    :param day: day of date logging
    :return: table of product logging
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    if request.user.is_superuser:
        if request.method == 'POST':
            context = Distributor().getLogInfo('%s-%s-%s' % (year, month, day), request.POST)
        else:
            context = Distributor().getLogInfo('%s-%s-%s' % (year, month, day))
        context['year'] = year
        context['month'] = month
        context['day'] = day
        return render_to_response('export/log_info.html', context, context_instance=RequestContext(request))
    return HttpResponseRedirect(reverse('home'))


def get_price_stek(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    if request.user.is_superuser:
        Stack().updatePrice()
        Distributor().updatePrice()
        year, month, day = str(date.today()).split('-')
        context = Distributor().getLogInfo('%s-%s-%s' % (year, month, day))
        sendReport(context, 'olexsbas@gmail.com', 'Daily report service %s-%s-%s' % (year, month, day))
        return HttpResponse('ok')
    return HttpResponseRedirect(reverse('home'))